package net.maku.framework.common.utils;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @author Administrator
 */
public class HttpGetUtil {


    private static final PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    private static final CloseableHttpClient httpClient;

    static {
        // 设置连接池参数
        connectionManager.setMaxTotal(200); // 设置最大连接数
        connectionManager.setDefaultMaxPerRoute(20); // 设置每个路由的最大连接数

        // 创建 HttpClient 实例
        httpClient = HttpClients.custom()
                .setConnectionManager(connectionManager)
                .build();
    }

    public static String httpRequestToString(String url, Map<String, String> params) {
        String result = null;
        try {
            // 构造请求 URL
            if (params != null && !params.isEmpty()) {
                StringBuilder parameters = new StringBuilder();
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    if (parameters.length() > 0) {
                        parameters.append("&");
                    }
                    parameters.append(entry.getKey()).append("=")
                            .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                }
                url += "?" + parameters.toString();
            }

            // 创建 HttpGet 请求
            HttpGet httpGet = new HttpGet(url);
            httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");
            httpGet.setHeader("Accept-Charset", "UTF-8");
            httpGet.setHeader("contentType", "utf-8");

            // 发送请求并获取响应
            CloseableHttpResponse response = httpClient.execute(httpGet);
            try {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 200) {
                    result = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
                } else {
                    System.err.println("HTTP 请求失败，状态码：" + statusCode);
                }
            } finally {
                response.close(); // 关闭响应
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    public static String httpRequestToString2(String url, Map<String, String> params) {
        String result = null;
        try {
            ReadableByteChannel channel = Channels.newChannel(httpRequestToStream(url, params));
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            StringBuilder sb = new StringBuilder();
            while (channel.read(buffer) != -1) {
                buffer.flip();
                sb.append(new String(buffer.array(), StandardCharsets.UTF_8));
                buffer.clear();
            }
            result = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;

    }

    private static InputStream httpRequestToStream(String url, Map<String, String> params) {
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            if (!(params == null)) {
                String parameters = "";
                boolean hasParams = false;
                for (String key : params.keySet()) {
                    String value = URLEncoder.encode(params.get(key), "UTF-8");
                    parameters += key + "=" + value + "&";
                    hasParams = true;
                }
                if (hasParams) {
                    parameters = parameters.substring(0, parameters.length() - 1);
                }

                url += "?" + parameters;
            }


            URL u = new URL(url);
            conn = (HttpURLConnection) u.openConnection();
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Accept-Charset", "UTF-8");
            conn.setRequestProperty("contentType", "utf-8");
            conn.setConnectTimeout(5000);
            conn.setReadTimeout(5000);
            conn.setDoInput(true);
            //设置请求方式，默认为GET
            conn.setRequestMethod("GET");

            is = conn.getInputStream();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return is;
    }

    /**
     * 发送 POST 请求
     *
     * @param url 请求的 URL
     * @param body 请求体内容（JSON 格式）
     * @return 响应内容
     * @throws Exception 如果发生网络错误或其他异常
     */
    public static String doPost(String url, String body)  {
        try {
            // 创建 URL 对象
            URL requestUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection();

            // 设置请求方法为 POST
            connection.setRequestMethod("POST");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            connection.setRequestProperty("Accept", "application/json");
            connection.setDoOutput(true);

            // 写入请求体
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = body.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }
            // 读取响应
            StringBuilder response = new StringBuilder();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
            }
            // 关闭连接
            connection.disconnect();
            // 返回响应内容
            return response.toString();
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

